import React, { Component } from "react";
import {
  Button,
  Table,
  Form,
  Select,
  DatePicker,
  Badge,
  message,
  Input
} from "antd";
import Zcon from "@cbd/icon";
import moment from "moment";
import { connect } from "dva";
import styles from "./Message.less";
import FormCom from "./FormCom";
import ExportBtn from "../../../../components/exportBtn";

const { Item } = Form;
const { RangePicker } = DatePicker;
const { Option } = Select;

const useful = data => {
  if (data === 1) {
    return <Badge status="success" text="有用" />;
  }
  if (data === 0) {
    return <Badge status="error" text="无用" />;
  }
  return "-";
};

const columns = [
  {
    title: "计划名称",
    dataIndex: "planName",
    fixed: "left",
    width: 100,
    render: text => (
      <span
        title={text}
        style={{
          width: 100,
          textOverflow: "ellipsis",
          display: "block",
          whiteSpace: "nowrap",
          overflow: "hidden"
        }}
      >
        {text}
      </span>
    )
  },
  {
    title: "推送场景",
    dataIndex: "templateName"
  },
  {
    title: "推送渠道",
    dataIndex: "pushChannelName"
  },
  {
    title: "推送目标",
    dataIndex: "receiverName"
  },
  {
    title: "归属部门",
    dataIndex: "ownerDeptName"
  },
  {
    title: "已读状态",
    dataIndex: "stateRead",
    filters: [{ text: "未读", value: 0 }, { text: "已读", value: 1 }],
    filterMultiple: false,
    render: text => (
      <div>
        {text === 1 ? (
          <Badge status="success" text="已读" />
        ) : (
          <Badge status="default" text="未读" />
        )}
      </div>
    )
  },
  {
    title: "是否有用",
    dataIndex: "grade",
    filters: [{ text: "有用", value: 1 }, { text: "无用", value: 0 }],
    filterMultiple: false,
    render: text => (
      <div>
        {useful(text)}
        {/* <font>{text}</font> */}
      </div>
    )
    // width: "20%"
  },
  {
    title: "状态",
    dataIndex: "pushResultCode",
    filters: [{ text: "失败", value: 0 }, { text: "成功", value: 1 }],
    filterMultiple: false,
    render: text => (
      <div>
        {text === 1 ? (
          <Badge status="success" text="成功" />
        ) : (
          <Badge status="error" text="失败" />
        )}
        {/* <font>{text}</font> */}
      </div>
    )
    // width: "20%"
  },
  {
    title: "反馈详情",
    dataIndex: "commentTextNew",
    // width: "9%",
    render: text => (
      <span
        title={text}
        style={{
          width: 60,
          textOverflow: "ellipsis",
          display: "block",
          whiteSpace: "nowrap",
          overflow: "hidden"
        }}
      >
        {text}
      </span>
    )
  },
  {
    title: "分发时间",
    dataIndex: "timeCreate",
    // fixed: "right",
    // width: 180,
    sorter: true,
    defaultSortOrder: "descend",
    render: text => <span>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</span>
    // width: "20%"
  }
];

@connect(stores => ({
  planData: stores.planlist,
  addPlanData: stores.addPlan,
  dsDetail: stores.adddataSource,
  situationData: stores.situationList,
  messageData: stores.message
}))
@Form.create()
class Message extends Component {
  state = { selected: [], show: false, exportLoading: false };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: "adddataSource/getOrgList",
      payload: {}
    });
    dispatch({ type: "addPlan/getPushChannel", payload: {} });
    dispatch({
      type: "situationList/getSituationList",
      payload: { pageNum: "1", pageSize: "10000" }
    });
    dispatch({ type: "addPlan/getPushChannel", payload: {} });
    dispatch({
      type: "planlist/planList",
      payload: {
        ascOrDesc: "desc",
        orderByClause: "time_create",
        pageNum: "1",
        pageSize: "1000"
      }
    });
    // dispatch({
    //   type: "adddataSource/getOrgList",
    //   payload: {}
    // });
  }

  setShow = () => {
    this.setState({
      show: true
    });
  };

  setNone = () => {
    this.setState({
      show: false
    });
  };

  handleSearch = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.onChange(
          values.planName,
          values.sceneName,
          values.channel,
          values.department,
          values.timeCreate
        );
        const { dispatch } = this.props;
        const temp = {
          planId: !values.planName ? "" : values.planName,
          sceneTemplateId: !values.sceneName ? "" : values.sceneName,
          pushChannelId: !values.channel ? "" : values.channel,
          ownerDept: !values.department ? "" : values.department,
          timeCreateStart:
            values.timeCreate && values.timeCreate.length
              ? values.timeCreate[0].format("YYYY-MM-DD HH:mm:ss")
              : "",
          timeCreateEnd:
            values.timeCreate && values.timeCreate.length
              ? values.timeCreate[1].format("YYYY-MM-DD HH:mm:ss")
              : "",
          stateRead:
            this.props.stateRead[0] && this.props.stateRead[0] !== ""
              ? this.props.stateRead[0] * 1
              : this.props.stateRead[0],
          grade:
            this.props.grade[0] && this.props.grade[0] !== ""
              ? this.props.grade[0] * 1
              : this.props.grade[0],
          pushResultCode:
            this.props.pushResultCode[0] && this.props.pushResultCode[0] !== ""
              ? this.props.pushResultCode[0] * 1
              : this.props.pushResultCode[0],
          ascOrDesc: this.props.ascOrDesc,
          queryCondition: values.planAddress
        };
        dispatch({
          type: "message/messageList",
          payload: {
            ...temp,
            pageNum: 1,
            pageSize: this.props.pageSize
          }
        });
        dispatch({
          type: "message/getDepart",
          payload: { pageNum: "1", pageSize: "10000", ...temp }
        });
      }
    });
  };

  handleReset = () => {
    this.props.form.resetFields();
    this.props.onChange("", "", "", "", "");
    const { dispatch } = this.props;
    const temp = {
      planId: "",
      sceneTemplateId: "",
      pushChannelId: "",
      ownerDept: "",
      timeCreateStart: "",
      timeCreateEnd: "",
      stateRead:
        this.props.stateRead[0] && this.props.stateRead[0] !== ""
          ? this.props.stateRead[0] * 1
          : this.props.stateRead[0],
      grade:
        this.props.grade[0] && this.props.grade[0] !== ""
          ? this.props.grade[0] * 1
          : this.props.grade[0],
      pushResultCode:
        this.props.pushResultCode[0] && this.props.pushResultCode[0] !== ""
          ? this.props.pushResultCode[0] * 1
          : this.props.pushResultCode[0],
      ascOrDesc: this.props.ascOrDesc,
      queryCondition: this.props.value
    };
    dispatch({
      type: "message/messageList",
      payload: {
        pageNum: 1,
        pageSize: this.props.pageSize,
        ...temp
      }
    });
    dispatch({
      type: "message/getDepart",
      payload: { pageNum: "1", pageSize: "10000", ...temp }
    });
  };

  exportExcel = type => {
    const {
      planName,
      sceneName,
      channel,
      department,
      startTime,
      endTime,
      stateRead,
      grade,
      pushResultCode,
      ascOrDesc,
      value,
      dispatch,
      messageList
    } = this.props;
    const { selected } = this.state;
    if (type !== "all" && selected.length <= 0) {
      message.error("请选择需要导出的内容");
      return;
    }
    if (type === "all" && messageList.length === 0) {
      message.error("该筛选条件下没有可导出数据");
      return;
    }
    this.setState({
      exportLoading: true
    });
    const handleLogIds = selected.map(item => item);
    const payload = {
      planId: planName,
      sceneTemplateId: sceneName,
      pushChannelId: channel,
      ownerDept: department,
      timeCreateStart: startTime,
      timeCreateEnd: endTime,
      stateRead:
        stateRead[0] && stateRead[0] !== "" ? stateRead[0] * 1 : stateRead[0],
      grade: grade[0] && grade[0] !== "" ? grade[0] * 1 : grade[0],
      pushResultCode:
        pushResultCode[0] && pushResultCode[0] !== ""
          ? pushResultCode[0] * 1
          : pushResultCode[0],
      ascOrDesc,
      pageNum: 1,
      pageSize: 10000,
      queryCondition: value,
      handleLogIds: type === "all" ? [] : handleLogIds
    };
    dispatch({
      type: "message/exportExcel",
      payload
    }).then(() => {
      const { errMsg } = this.props.messageData;
      if (!errMsg) {
        message.success("导出成功");
      } else {
        message.error("导出失败，".concat(errMsg));
        dispatch({
          type: "message/get/errMsg",
          payload: ""
        });
      }
      this.setState({
        exportLoading: false
      });
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const {
      dsDetail,
      planData,
      addPlanData,
      situationData,
      messageData
    } = this.props;
    const { departData = [] } = messageData;
    const { orgTree = [] } = dsDetail;
    const { STList = [] } = situationData;
    const { channelList = [] } = addPlanData;
    const { planList = [] } = planData;
    const { show, exportLoading } = this.state;
    const rowSelection = {
      onSelect: (items, e) => {
        const { selected } = this.state;
        if (!e) {
          this.setState({
            selected: Array.from(
              new Set(selected.filter(i => i !== items.handleLogId))
            )
          });
        } else {
          selected.push(items.handleLogId);
          this.setState({
            selected: Array.from(new Set(selected))
          });
        }
      },
      onSelectAll: (status, items, changed) => {
        const { selected } = this.state;
        if (status) {
          changed.forEach(i => {
            selected.push(i.handleLogId);
          });
          this.setState({
            selected: Array.from(new Set(selected))
          });
        } else {
          let temp = selected;
          changed.forEach(i => {
            temp = temp.filter(item => item !== i.handleLogId);
          });
          this.setState({
            selected: temp
          });
        }
      }
    };

    // const { history } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 0 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 0 },
        sm: { span: 16 }
      }
    };
    return (
      <div className={styles.root}>
        {show ? (
          <div className={styles.topSel}>
            <FormCom
              planList={planList}
              orgTree={orgTree}
              channelList={channelList}
              STList={STList}
              setNone={this.setNone}
              handleSearch={this.handleSearch}
              handleReset={this.handleReset}
              getFieldDecorator={getFieldDecorator}
              departData={departData}
              onSearch={this.props.onSearch}
            />
          </div>
        ) : null}
        <div className={styles.btm}>
          <div style={{ display: "flex" }}>
            <ExportBtn
              exportExcel={type => this.exportExcel(type)}
              loading={exportLoading}
            />
            {!show ? (
              <Form onSubmit={this.handleSearch}>
                <div style={{ width: "100%", marginTop: -4 }}>
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "flex-end",
                      alignItems: "center"
                    }}
                  >
                    <Item
                      label="推送目标："
                      {...formItemLayout}
                      style={{ width: 320, marginRight: 10 }}
                    >
                      {getFieldDecorator(`planAddress`)(
                        <Input
                          placeholder="推送目标"
                          size="default"
                          style={{ width: 250 }}
                        />
                      )}
                    </Item>
                    <Item
                      label="分发时间："
                      {...formItemLayout}
                      style={{ width: 320, marginRight: 10 }}
                    >
                      {getFieldDecorator(`timeCreate`)(
                        <RangePicker
                          showTime
                          // style={{ width:  }}
                          style={{ width: 250 }}
                        />
                      )}
                    </Item>
                    {/* <Item
                      label="计划名称："
                      {...formItemLayout}
                      style={{ width: 320, marginRight: 32 }}
                    >
                      {getFieldDecorator(`planName`)(
                        <Select
                          placeholder="请选择计划名称"
                          style={{ width: 250 }}
                        >
                          {planList.map(item => (
                            <Option key={item.planId} value={item.planId}>
                              {item.planName}
                            </Option>
                          ))}
                        </Select>
                      )}
                    </Item>
                    <Item
                      label="推送场景："
                      {...formItemLayout}
                      style={{ width: 320, marginRight: 32 }}
                    >
                      {getFieldDecorator(`sceneName`)(
                        <Select
                          placeholder="请选择推送场景"
                          style={{ width: 250 }}
                        >
                          {STList.map(item => (
                            <Option
                              value={`${item.sceneTemplateId}`}
                              key={item.sceneTemplateId}
                            >
                              {item.templateName}
                            </Option>
                          ))}
                        </Select>
                      )}
                    </Item> */}
                    <div
                      style={{
                        display: "flex"
                      }}
                    >
                      <Button
                        style={{ marginRight: 8, marginTop: -24 }}
                        type="primary"
                        htmlType="submit"
                      >
                        查询
                      </Button>
                      <Button
                        style={{ marginRight: 11, marginTop: -24 }}
                        onClick={this.handleReset}
                      >
                        重置
                      </Button>
                      <Zcon
                        type="down-o"
                        style={{
                          width: 16,
                          fontSize: 16,
                          color: "rgba(0,0,0,0.65)",
                          fontWeight: 500,
                          marginTop: -16
                        }}
                        onClick={this.setShow}
                      />
                    </div>
                  </div>
                  <div style={{ display: "none" }}>
                    <Item
                      label="推送渠道："
                      {...formItemLayout}
                      style={{ width: 320 }}
                    >
                      {getFieldDecorator(`channel`)(
                        <Select
                          placeholder="请选择推送渠道"
                          style={{ width: 250 }}
                        >
                          {channelList.map(item => (
                            <Option
                              value={item.pushChannelId * 1}
                              key={item.pushChannelId}
                            >
                              {item.description}
                            </Option>
                          ))}
                        </Select>
                      )}
                    </Item>
                    <Item
                      label="归属部门："
                      {...formItemLayout}
                      style={{ width: 320 }}
                    >
                      {getFieldDecorator(`department`)(
                        // <TreeSelect
                        //   treeData={orgTree}
                        //   placeholder="请选择归属部门"
                        //   style={{ width: 250 }}
                        //   dropdownStyle={{ maxHeight: 350, overflow: "auto" }}
                        //   showCheckedStrategy="SHOW_PARENT"
                        // />
                        <Select placeholder="请选择归属部门">
                          {departData.map(item => (
                            <Option key={item.ownerDept} value={item.ownerDept}>
                              {item.ownerDeptName}
                            </Option>
                          ))}
                        </Select>
                      )}
                    </Item>
                    <Item
                      label="分发时间："
                      {...formItemLayout}
                      style={{ width: 320 }}
                    >
                      {getFieldDecorator(`timeCreate`)(
                        <RangePicker
                          showTime
                          // style={{ width:  }}
                          style={{ width: 250 }}
                        />
                      )}
                    </Item>
                  </div>
                </div>
              </Form>
            ) : null}
          </div>
          <Table
            columns={columns}
            size="middle"
            locale={{ emptyText: "暂无数据！" }}
            rowKey={record => record.handleLogId}
            dataSource={this.props.messageList}
            scroll={this.props.messageList.length===0?{x:false}:{ x: 1440 }}
            style={{ marginTop: show ? 16 : -8 }}
            loading={this.props.loading}
            onChange={(e, filters, sorter) =>
              this.props.handleTableChange(e, filters, sorter)
            }
            rowSelection={rowSelection}
            pagination={{
              defaultPageSize: 10,
              showQuickJumper: true,
              showSizeChanger: true,
              current: this.props.pageNum,
              total: this.props.totalCount,
              showTotal: total => `共有 ${total} 条`
            }}
          />
        </div>
      </div>
    );
  }
}

export default Message;
